from bs4 import BeautifulSoup as bs4
import requests as req
import sys
import json
# smtplib 用于邮件的发信动作
import os
import base64
from smtplib import SMTP
import schedule
from email.mime.text import MIMEText
# email 用于构建邮件内容
from email.header import Header
import gl_var as gv
import time
import sqlMapper

def inform(subjectInfo):

    # 发信方的信息：发信邮箱，QQ 邮箱授权码
    from_addr = gv.from_mail_address
    password = gv.password
    
    # 收信方邮箱
    # to_addrs =gv.to_mail_addresses
    to_addrs =sqlMapper.getEmailList()
    
    # 发信服务器
    smtp_server = gv.smtp_server
    
    # 邮箱正文内容，第一个参数为内容，第二个参数为格式(plain 为纯文本)，第三个参数为编码

    msg = MIMEText(subjectInfo["summary"],"plain","utf-8")
    
    # 邮件头信息
    msg['from'] = "zsx<18115201784@163.com>"
    msg['to'] ="小助手"
    msg['subject'] = Header(subjectInfo["title"],'utf-8')
    
    # 开启发信服务，这里使用的是加密传输
    server = SMTP(smtp_server)
    # 登录发信邮箱
    server.login(from_addr, password)
    print(msg.as_string())
    # 发送邮件
    server.sendmail(from_addr, to_addrs, msg.as_string())
    # 关闭服务器
    server.quit()

def spider():

    dxyHtmlContent=req.get("https://3g.dxy.cn/newh5/view/pneumonia_peopleapp?from=timeline&isappinstalled=0").content.decode("utf-8")
    bs=bs4(dxyHtmlContent,'html.parser')
    html=bs.find(id="getTimelineService").contents
    _guolv_header_len=len("try { window.getTimelineService = ")
    _guolv_end_len=len('}catch(e){}')
    html_json=html[0][_guolv_header_len:len(html)-_guolv_end_len-1]
    html_json=json.loads(html_json)
    lastest_info=html_json[0]
    if gv.gl_latest_id != lastest_info["id"]:
        gv.gl_latest_id=lastest_info["id"]
        print("当前gl_id:"+str(gv.gl_latest_id))
        inform(lastest_info)

schedule.every(2).minutes.do(spider)
while True:
    schedule.run_pending()
    time.sleep(1)


